package cn.flying.cloud.oauth.server.configuration.provider;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import cn.flying.cloud.base.common.constants.Constants;
import cn.flying.cloud.base.redis.service.RedisService;
import cn.flying.cloud.oauth.server.configuration.authentication.SmsCodeAuthenticationToken;
import cn.flying.cloud.oauth.server.configuration.details.CustomUserDetailService;
import cn.flying.cloud.oauth.server.configuration.exception.SmsCodeOAuthException;

/**
 * 验证码授权模式登录
 *
 * @author: admin
 * @date: 2024年05月16日 16:59
 * @version: 1.0
 */
@Component
public class SmsCodeAuthenticationProvider implements AuthenticationProvider {

    private static final String SMS_CODE_PREFIX = ":sms:code:";

    @Resource
    private CustomUserDetailService userDetailService;
    @Resource
    private RedisService redisService;

    /**
     * Performs authentication with the same contract as
     * {@link AuthenticationManager#authenticate(Authentication)}
     * .
     *
     * @param authentication the authentication request object.
     * @return a fully authenticated object including credentials. May return
     * <code>null</code> if the <code>AuthenticationProvider</code> is unable to support
     * authentication of the passed <code>Authentication</code> object. In such a case,
     * the next <code>AuthenticationProvider</code> that supports the presented
     * <code>Authentication</code> class will be tried.
     * @throws AuthenticationException if authentication fails.
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        SmsCodeAuthenticationToken authenticationToken = (SmsCodeAuthenticationToken) authentication;
        String username = (String) authenticationToken.getPrincipal();
        String code = (String) authenticationToken.getCredentials();

        // 尝试从Redis中取出code
        String codeKey = Constants.AUTH_CODE + SMS_CODE_PREFIX + username;
        String cacheCode = (String) redisService.get(codeKey);
        if (StringUtils.isBlank(cacheCode) || !code.equalsIgnoreCase(cacheCode)) {
            throw new SmsCodeOAuthException("验证码不正确！");
        } else {
            redisService.del(codeKey);
        }
        UserDetails userDetails = userDetailService.loadUserByUsername(username);

        //这里的主体要设置为用户信息
        SmsCodeAuthenticationToken token = new SmsCodeAuthenticationToken(userDetails.getAuthorities(), userDetails, code);
        token.setDetails(userDetails);
        return token;
    }

    /**
     * Returns <code>true</code> if this <Code>AuthenticationProvider</code> supports the
     * indicated <Code>Authentication</code> object.
     * <p>
     * Returning <code>true</code> does not guarantee an
     * <code>AuthenticationProvider</code> will be able to authenticate the presented
     * instance of the <code>Authentication</code> class. It simply indicates it can
     * support closer evaluation of it. An <code>AuthenticationProvider</code> can still
     * return <code>null</code> from the {@link #authenticate(Authentication)} method to
     * indicate another <code>AuthenticationProvider</code> should be tried.
     * </p>
     * <p>
     * Selection of an <code>AuthenticationProvider</code> capable of performing
     * authentication is conducted at runtime the <code>ProviderManager</code>.
     * </p>
     *
     * @param authentication
     * @return <code>true</code> if the implementation can more closely evaluate the
     * <code>Authentication</code> class presented
     */
    @Override
    public boolean supports(Class<?> authentication) {
        return SmsCodeAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
